package com.buildings.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.buildings.R;
import com.buildings.activity.LoginActivity;
import com.buildings.activity.MainTabActivity;
import com.buildings.activity.TaskMapActivity;
import com.buildings.activity.TownHouseFormActivity;
import com.buildings.activity.TownNonHouseFormActivity;
import com.buildings.activity.VillageHouseFormActivity;
import com.buildings.activity.VillagePublicFormActivity;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.bean.LoginBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.Base64Test;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.SPUtil;
import com.githang.statusbar.StatusBarCompat;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;

/**
 * Created by songwei on 2017/7/31.
 */

public class BaseActivity extends AppCompatActivity {

    public TextView tvTitle;
    public Activity activity;
    private FinishBroadcastReceiver finishBroadcastReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
//        initSystemBarTint();
//        LightStatusBarUtils.setLightStatusBar(activity, true);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.setStatusBarColor(activity, getResources().getColor(R.color.white), true);
        }
        tvTitle = (TextView) findViewById(R.id.tv_title);
        initFinish();
    }

    private void initFinish(){
        finishBroadcastReceiver = new FinishBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(activity.getClass().getName());
        registerReceiver(finishBroadcastReceiver,intentFilter);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(finishBroadcastReceiver);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


//    @TargetApi(19)
//    public  void setTranslucentStatus(boolean on) {
//        Window win = getWindow();
//        WindowManager.LayoutParams winParams = win.getAttributes();
//        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//        if (on) {
//
//            winParams.flags |= bits;
//        } else {
//
//            winParams.flags &= ~bits;
//        }
//
//        win.setAttributes(winParams);
//    }

//    /** 子类可以重写改变状态栏颜色 */
//    protected int setStatusBarColor() {
//        return getColorPrimary();
//    }
//
//    /** 子类可以重写决定是否使用透明状态栏 */
//    protected boolean translucentStatusBar() {
//        return false;
//    }


    /** 设置状态栏颜色 */
//    protected void initSystemBarTint() {
//        Window window = getWindow();
//        if (translucentStatusBar()) {
//            // 设置状态栏全透明
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//                window.setStatusBarColor(Color.TRANSPARENT);
//            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            }
//            return;
//        }
//        // 沉浸式状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            //5.0以上使用原生方法
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(setStatusBarColor());
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
////            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintColor(setStatusBarColor());
//        }
//    }

    /** 获取主题色 */
//    public int getColorPrimary() {
//        TypedValue typedValue = new TypedValue();
//        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
//        return typedValue.data;
//    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.left_to_right, R.anim.to_right);
    }

    public void finish(int type) {
        super.finish();
        if(type == 1){
            overridePendingTransition(R.anim.left_to_right, R.anim.to_right);
        }else if( type == 2){
            overridePendingTransition(R.anim.right_to_left, R.anim.to_left);
        }else if(type == 3){
            overridePendingTransition(R.anim.up_to_down, R.anim.to_down);
        }
    }

    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.right_to_left, R.anim.to_left);
    }

    public void startActivity(Intent intent, int type) {
        super.startActivity(intent);
    }

    public void Toast(String message){

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    // 双击事件记录最近一次点击的时间
    protected long lastClickTime;
    /*
* 保存MyTouchListener接口的列表
*/
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();

    public interface MyTouchListener {
        boolean onTouchEvent(MotionEvent event);
    }
    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     *
     * @param listener
     */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    class FinishBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("finish111",action);
            if(TextUtils.equals(action,activity.getClass().getName())){
                finish();
            }
        }
    }


    /**
     * 用于用户定位，调用天地图的js
     */
    public void updateLocation(){

        final WebView webView = new WebView(activity);
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        WebSettings webSettings = webView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setJavaScriptEnabled(true);//启用js
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setGeolocationDatabasePath( getFilesDir().getPath() );
        webSettings.setDatabaseEnabled(true);//
        webSettings.setGeolocationEnabled(true);//
        webView.addJavascriptInterface(new MyJavaInterface(),"androidObject");
//支持缩放，默认为true。
        webSettings.setSupportZoom(true);
//调整图片至适合webview的大小
        webSettings.setUseWideViewPort(true);
// 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
//设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError errorResponse) {
                super.onReceivedError(view, request, errorResponse);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下执行
                //网络未连接
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String params = "'0','0'";
                webView.loadUrl("javascript:getLocation("+params+")");


            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.loadUrl("file:///android_asset/map.html");
    }

    public class MyJavaInterface {

        @JavascriptInterface
        public void androidMapClick(final String lng, final String lat,final String locationLng,final String locationLat){
            //横竖屏切换  0竖屏   1横屏 somehowTheScreen
            Log.e("经纬度",lng+","+lat);
            Log.e("经纬度",locationLng+","+locationLat);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    myLocation(locationLng, locationLat);
                }
            });

        }
    }

    public void myLocation(String locationLng, String locationLat){

    }


    /**
     * 保存活动轨迹
     */
    public void updateFoot(String userId,String taskId,String longitude,String latitude) {
       // private String userId;用户Id
       // private String taskId;任务ID
       // private String longitude;经度
       // private String latitude;纬度

        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("userId", userId);
        jsonBuilder.put("taskId", taskId);
        jsonBuilder.put("longitude", longitude);
        jsonBuilder.put("latitude", latitude);

        MyHttpClient
                .newBuilder()
                .post()
                .url(Api.SAVE_FOOT)
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean bean) {
                        super.onSuccess(bean);


                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                    }
                });

    }




}
